package com.heimali.happyreader;

import com.heimali.happyreader.config.Constants;
import com.heimali.happyreader.config.PersonalConfig;
import com.heimali.happyreader.db.DBHelper;
import com.heimali.happyreader.model.UpdateInfo;
import com.heimali.happyreader.utils.NetUtils;
import com.heimali.happyreader.utils.SystemUtils;
import com.heimali.happyreader.wraper.BaseWraper;
import com.heimali.happyreader.wraper.UpdateWraper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class BaseActivity extends Activity implements OnClickListener {

	protected Button progressBarRetryButton;
	protected LinearLayout emptyLayout;
	protected LinearLayout noArticleListLayout;
	protected AnimationDrawable frameAnimation;
	protected LinearLayout progressBarLayout;
	protected LinearLayout progressBarFailedLayout;
	protected ImageView progressBarLoading;

	public static LoginActivity loginEntity = null;

	public BaseActivity() {

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	protected void initProgressBar() {
		emptyLayout = (LinearLayout) findViewById(R.id.empty_layout);
		noArticleListLayout = (LinearLayout) findViewById(R.id.no_article_list_layout);
		progressBarLayout = (LinearLayout) findViewById(R.id.progress_bar);
		progressBarLoading = (ImageView) findViewById(R.id.progress_bar_loading);
		progressBarFailedLayout = (LinearLayout) findViewById(R.id.progress_bar_error);
		frameAnimation = (AnimationDrawable) progressBarLoading.getBackground();
		progressBarRetryButton = (Button) findViewById(R.id.progress_bar_retry);
		progressBarRetryButton.setOnClickListener(this);
	}

	protected void progressBarStrat(View mainView) {
		if (noArticleListLayout != null) {
			noArticleListLayout.setVisibility(View.GONE);
		}
		emptyLayout.setVisibility(View.GONE);
		mainView.setVisibility(View.GONE);
		progressBarLayout.setVisibility(View.VISIBLE);
		progressBarFailedLayout.setVisibility(View.GONE);
		if (frameAnimation != null && !frameAnimation.isRunning()) {
			frameAnimation.start();
		}
	}

	protected void progressBarStop(View mainView, boolean isSuccessful) {
		if (frameAnimation != null && frameAnimation.isRunning()) {
			frameAnimation.stop();
		}
		if (isSuccessful) {
			progressBarLayout.setVisibility(View.GONE);
			mainView.setVisibility(View.VISIBLE);
		} else {
			progressBarLayout.setVisibility(View.GONE);
			progressBarFailedLayout.setVisibility(View.VISIBLE);
		}
	}

	public void onClick(View v) {
	}

	@Override
	public void onLowMemory() {
		super.onLowMemory();
		System.gc();
	}

	/**
	 * 最后检查更新时间更新为当前时间
	 */
	private void updateLastCheckUpdateTime() {
		setLastCheckUpdateTime(SystemUtils.getCurrentDate());
	}

	/**
	 * 设置最后检查更新时间
	 * 
	 * @param today
	 */
	private void setLastCheckUpdateTime(String today) {
		PersonalConfig.getInstance().setConfig(Constants.COMMON_CONFIG_LAST_CHECK_UPDATE_TIME, today);
	}

	/**
	 * 自动检查新版本
	 */
	protected void autoCheckNewVersion() {
		final String today = SystemUtils.getCurrentDate();
		String lastCheckTime = PersonalConfig.getInstance().getConfig(Constants.COMMON_CONFIG_LAST_CHECK_UPDATE_TIME,
				"");
		if (today.equals(lastCheckTime)) {
			return;
		}

		new UpdateWraper(new BaseWraper.Callback() {
			public void onSuccess(Object result) {
				setLastCheckUpdateTime(today);
				int versionCode = SystemUtils.getVersionCode();
				UpdateInfo info = (UpdateInfo) result;
				if (info.minVerCode > versionCode) {
					forceUpdate(info);
				} else if (info.verCode > versionCode) {
					confirmUpdate(info);
				}
			}

			public void onFail(int errno, String errmsg) {
				setLastCheckUpdateTime(today);
			}
		}).execute();
	}

	protected void checkUpdate() {
		if (!NetUtils.isNetAvailable()) {
			Toast.makeText(BaseActivity.this, getString(R.string.network_not_available), 0).show();
			return;
		}

		final ProgressDialog pd = new ProgressDialog(BaseActivity.this);
		pd.setMessage(getString(R.string.update_checking));
		pd.show();
		new UpdateWraper(new BaseWraper.Callback() {
			public void onSuccess(Object result) {
				pd.dismiss();
				updateLastCheckUpdateTime();
				int versionCode = SystemUtils.getVersionCode();
				UpdateInfo info = (UpdateInfo) result;
				if (info.minVerCode > versionCode) {
					forceUpdate(info);
				} else if (info.verCode > versionCode) {
					confirmUpdate(info);
				} else {
					notUpdate();
				}
			}

			public void onFail(int errno, String errmsg) {
				pd.dismiss();
				Toast.makeText(BaseActivity.this, getString(R.string.update_check_error), 0).show();
				updateLastCheckUpdateTime();
			}
		}).execute();
	}

	/**
	 * 不需要升级
	 */
	private void notUpdate() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setIcon(android.R.drawable.ic_dialog_info).setTitle(R.string.tip)
				.setMessage(getString(R.string.update_not_need_update))
				.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
					}
				}).create().show();
	}

	/**
	 * 需要确认的升级方式
	 * 
	 * @param info
	 */
	private void confirmUpdate(final UpdateInfo info) {
		String msg = getString(R.string.update_msg_normal_update, info.verName);
		String updates = getString(R.string.update_msg_normal_update_title, info.verName);

		AlertDialog.Builder builder = new Builder(this);
		builder.setIcon(android.R.drawable.ic_dialog_info).setTitle(R.string.tip)
				.setMessage(msg + "\n\n" + updates + "\n" + info.description + "\n")
				.setPositiveButton(R.string.update_now, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.setData(Uri.parse(info.url));
						startActivity(intent);
					}
				}).setNegativeButton(R.string.update_skip, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
					}
				}).create().show();
	}

	/**
	 * 强制升级到最低版本的升级方式
	 * 
	 * @param info
	 */
	private void forceUpdate(UpdateInfo info) {

	}

	protected void logout(final Context context) {
		AlertDialog.Builder builder = new Builder(this);
		builder.setIcon(android.R.drawable.ic_dialog_info).setTitle(R.string.tip).setMessage(R.string.is_logout)
				.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(context, LoginActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						context.startActivity(intent);
						finish();
						Statics.logout();
						DBHelper.logout();
					}
				}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				}).create().show();
	}

	protected void exit() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setIcon(android.R.drawable.ic_dialog_info).setTitle(R.string.tip).setMessage(R.string.is_exit)
				.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						finish();
						if (loginEntity != null) {
							loginEntity.finish();
							loginEntity = null;
						}
						// Statics.logout();
						DBHelper.logout();
						System.exit(0);
					}
				}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				}).create().show();
	}

	protected void checkLogin() {
		if (!Statics.isLogin()) {
			Intent intent = new Intent(this, LoginActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			finish();
		}
	}

	protected void startOfflineDownload() {
		Toast.makeText(this, getString(R.string.offline_download_start), 0).show();
		startService(new Intent(Constants.DOWNLOAD_SERVICE_NAME));
	}

	protected void stopOfflineDownload() {
		Toast.makeText(this, getString(R.string.offline_download_cancel), 0).show();
		stopService(new Intent(Constants.DOWNLOAD_SERVICE_NAME));
	}

}
